# coding=utf-8
#!/usr/bin/env python


import wsgiref.handlers

import os
import yaml
import re
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from django.utils import simplejson
from status import Status
from twitter import TwitterClient

#メインページ
class MainHandler(webapp.RequestHandler):
  config = yaml.safe_load(open(os.path.join(os.path.dirname(__file__), 'config.yaml'), 'r'))
  username = config['twitter_username']
  yjdn_appid = config['yjdn_appid']
 
  def get(self):
    twitter = TwitterClient()
    users = twitter.getReplyUsers()
    statuses = Status.getStatuses(20)
    list = []
    for status in statuses:
      if not status.user_id in users:
        continue
      if status.loc_point :
        list.append( {
          'id'    : status.id,
          'user'  : users[status.user_id],
          'text'  : status.text,
          'reply' : self.URLify(status.reply),
          'url'   : status.loc_url,
          'lat'   : status.loc_point.lat,
          'lon'   : status.loc_point.lon,
        })
      else :
        list.append( {
          'user'  : users[status.user_id],
          'text' : status.text,
          'reply' : self.URLify( status.reply ),
          'url'   : status.loc_url,
        })

    user = twitter.getUser( self.username )
    values = { 'appid'  : self.yjdn_appid,
               'list'   : list,
               'user'   : user,
               'list_json' : simplejson.dumps(list),
                }
    path = os.path.join(os.path.dirname(__file__), 'main.html')
    self.response.out.write( template.render(path,values))

  def URLify(self,txt):
    if txt:
      txt = re.sub('(https?:\/\/[-_.!~*\'()a-zA-Z0-9;/?:@&=+$,%#]+)',  
                 '<a href="\\1">Link</a>', txt)
    return txt



def main():
  application = webapp.WSGIApplication([('/', MainHandler),],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
